import 'dart:convert';
import 'dart:io';
import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:flutter_ohos/app/common/global.dart';
import 'package:flutter_ohos/app/common/widgets/toast.dart';

import '../http_config.dart';

const apikey = "";
const secret = "";

class CustomInterceptors extends InterceptorsWrapper {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // 头部添加header
    if(Global.getToken().isNotEmpty){
      options.headers[HttpHeaders.authorizationHeader] = 'Bearer'+Global.getToken();
    }

    if (Platform.isIOS) {
      options.headers['platform'] = "store_ios";
    } else if (Platform.isAndroid) {
      options.headers['platform'] = "store_android";
    }

    ///时间戳
    final timestamp = DateTime.now().microsecondsSinceEpoch;
    ///签名
    var signStr = ("$apikey$secret$timestamp");
    signStr = '${sha256.convert(utf8.encode(signStr))}';

    options.headers['apikey'] = apikey;
    options.headers['timestamp'] = timestamp;
    options.headers['apiversion'] = 2;
    options.headers['sign'] = signStr;

    options.baseUrl = HttpConfig.baseURL;
    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // 根据业务需求进行定制化处理
    handler.next(response);
  }

  @override
  void onError(DioException exception, ErrorInterceptorHandler handler) {
    switch (exception.type) {
      /// 连接服务器超时
      case DioExceptionType.connectionTimeout:{
        showToast("连接服务器超时");
      }
      break;
      /// 响应超时
      case DioExceptionType.receiveTimeout:{
        showToast("响应超时");
      }
      break;
      /// 发送超时
      case DioExceptionType.sendTimeout:{
        showToast("发送超时");
      }
      break;
      /// 请求取消
      case DioExceptionType.cancel:{
        showToast("请求取消");
      }
      break;
      /// 404/503错误
      case DioExceptionType.badResponse:{
        showToast("服务端内部错误");
      }
      break;
      // other 其他错误类型
      case DioExceptionType.unknown:{
        showToast("网络连接失败，请查看网络相关设置");
      }
        break;
    }
    super.onError(exception, handler);
  }
}
